<template>
  <div class="table-container">
    <search-bar v-model="queryParams" :config="searchColumn" @search="handleSearch" @searchReset="handleReset" key="users" />
    <table-page
      width="100%"
      class="role-table"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :isIndex="true"
      :isSelection="false"
      :indexFixed="true"
      :total="pages.total"
      :pageSize="pages.pageSize"
      :currentPage="pages.pageNum"
      :indexWidth="120"
      indexAlign="left"
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
    >
      <template #handle>
        <el-button
          class="m_96"
          type="primary"
          v-hasPermi="['CentralControl.IdentityRole.Create']"
          icon="el-icon-plus"
          @click="handleRoleDialog('新增')"
        >
          角色
        </el-button>
      </template>
    </table-page>

    <!-- 新增/编辑角色 -->
    <el-dialog
      width="30%"
      class="app-dialog"
      :title="`${roleDialogType}角色`"
      :visible.sync="roleDialogVisible"
      :before-close="handleRoleDialogClose"
      :close-on-click-modal="false"
    >
      <Form class="role-add" style="padding: 10px 0" ref="roleEdit" v-model="roleDialogData" :config="roleDialogConfig" label-position="top" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleRoleDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleRoleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限弹窗 -->
    <el-dialog
      width="40%"
      class="app-dialog"
      title="编辑权限"
      :visible.sync="authDialogVisible"
      :before-close="handleAuthDialogClose"
      :close-on-click-modal="false"
    >
      <div class="container" style="height: 450px; overflow-y: scroll" v-if="authDialogVisible">
        <el-tree
          ref="authTree"
          show-checkbox
          :data="authOptions"
          node-key="name"
          :props="{
            value: 'name',
            label: 'displayName',
            children: 'children',
          }"
          :default-expand-all="true"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAuthDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleAuthSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Form from '@/components/Form'
import SearchBar from '@/components/SearchBar'
import TablePage from '@/components/TablePage'
import { addRole, putRole, delRole, getRoleList, getUserPermissions, putUserPermissions } from '@/api/identity'

export default {
  name: 'RoleSearchTable',
  components: {
    SearchBar,
    TablePage,
    Form,
  },
  props: {
    uid: { type: String, required: true },
  },
  data: function () {
    return {
      queryParams: {},
      searchColumn: [
        {
          prop: 'name',
          type: 'input',
          placeholder: '角色名称',
        },
        // {
        //   prop: 'isOn',
        //   type: 'select',
        //   placeholder: '是否启用',
        //   options: [
        //     { label: '启用', value: 1 },
        //     { label: '未启用', value: 0 },
        //   ],
        // },
      ],
      tableData: [],
      tableColumn: [
        {
          label: '角色名称',
          prop: 'name',
          align: 'left',
        },
        // {
        //   label: '所属组织',
        //   prop: 'dept',
        // },
        // {
        //   label: '是否启用',
        //   prop: 'isOn',
        //   type: 'switch',
        //   align: 'center',
        // },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          width: '150px',
          type: 'button',
          buttons: [
            {
              label: '编辑',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleEdit',
              policy: ['CentralControl.IdentityRole.Update'],
            },
            {
              label: '权限',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleAuth',
              policy: ['CentralControl.IdentityRole.Permission'],
            },
            {
              label: '删除',
              type: 'text',
              color: '#F37272',
              method: 'handleDelete',
              policy: ['CentralControl.IdentityRole.Delete'],
            },
          ],
        },
      ],
      roleDialogType: '',
      roleDialogData: {},
      roleDialogVisible: false,
      roleDialogConfig: [
        {
          label: '角色名称',
          prop: 'name',
          type: 'input',
          maxlength: 30,
          placeholder: '请输入角色名称',
          rules: [{ required: true, trigger: 'blur', message: '请输入角色名称' }],
        },
      ],
      // 权限编辑弹窗
      authDialogVisible: false,
      authOptions: [],
      providerKey: '',
      checkedKeys: [],
      changeNodes: [],
      pages: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  watch: {
    uid: {
      handler: function (nval) {
        this.getTableData(nval)
      },
      immediate: true,
    },
  },
  mounted() {
    // 编辑角色
    this.$bus.$on('handleEdit', rows => {
      this.roleDialogData = { ...rows }
      this.handleRoleDialog('编辑')
    })

    // 权限
    this.$bus.$on('handleAuth', rows => {
      this.providerKey = 'CentralControl_' + rows.name
      getUserPermissions({ providerKey: this.providerKey, providerName: 'R' }).then(res => {
        this.convertTree(res)
        this.authDialogVisible = true
      })
    })

    // 删除角色
    this.$bus.$on('handleDelete', rows => {
      this.$confirm(`确认删除角色名为" ${rows.name} "的角色吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delRole(rows.id).then(res => {
          if (this.pages.total % this.pages.pageSize === 1) {
            const lastpage = (this.pages.total + this.pages.pageSize - 1) / this.pages.pageSize
            if (this.pages.pageNum == lastpage) {
              this.pages.pageNum = this.pages.pageNum - 1
            }
          }
          this.getTableData(this.uid)
          this.$message({ type: 'success', message: '删除角色成功!' })
        })
      })
    })
  },
  destroyed() {
    this.$bus.$off('handleEdit')
    this.$bus.$off('handleAuth')
    this.$bus.$off('handleDelete')
  },
  methods: {
    getTableData() {
      const params = {
        ouId: this.uid,
        SkipCount: ((this.pages.pageNum <= 1 ? 1 : this.pages.pageNum) - 1) * this.pages.pageSize,
        MaxResultCount: this.pages.pageSize,
        ...this.queryParams,
      }
      getRoleList(params).then(res => {
        this.tableData = res.items
        this.pages.total = res.totalCount
      })
    },
    handleSearch() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleReset() {},
    // 新增/编辑角色
    async handleRoleSubmit() {
      const flag = await this.$refs.roleEdit.validate()
      if (!flag) return
      this.roleSubmitFunc({
        isAdd: true,
        orgId: null,
        fullName: null,
        displayName: null,
        currentNodeKey: null,
        id: this.roleDialogData.id || null,
        name: `CentralControl_${this.roleDialogData.name}`,
      })
    },
    async roleSubmitFunc(data) {
      const id = this.roleDialogData.id
      id ? await putRole(data) : await addRole(data)
      this.getTableData()
      this.handleRoleDialogClose()
      this.$message.success(`角色${this.roleDialogType}成功`)
    },
    handleRoleDialog(string) {
      this.roleDialogType = string
      this.roleDialogVisible = true
    },
    handleRoleDialogClose() {
      this.roleDialogData = {}
      this.$refs.roleEdit.resetFields()
      this.roleDialogVisible = false
    },
    handleAuthDialogClose() {
      this.authDialogVisible = false
    },
    handleSizeChange(v) {
      this.pages.pageSize = v
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleCurrentChange(v) {
      this.pages.pageNum = v
      this.getTableData()
    },
    handleAuthSubmit() {
      this.changeNodes = []
      let checkedKeys = this.$refs.authTree.getCheckedKeys()
      checkedKeys.forEach(item => {
        if (this.checkedKeys.indexOf(item) == -1) {
          this.changeNodes.push({ isGranted: true, name: item })
        }
      })
      this.checkedKeys.forEach(item => {
        if (checkedKeys.indexOf(item) == -1) {
          this.changeNodes.push({ isGranted: false, name: item })
        }
      })
      putUserPermissions(this.providerKey, 'R', {
        permissions: this.changeNodes,
      }).then(res => {
        this.$message.success('操作成功')
        this.handleAuthDialogClose()
      })
    },
    convertTree(data) {
      let treeList = []
      let checkedArray = []
      function setChild(arr, item) {
        let parentList = arr.filter(a => a.parentName == item.name)
        if (item.isGranted) {
          checkedArray.push(item.name)
        }
        if (parentList && parentList.length > 0) {
          item.children = parentList
          item.children.map(child => {
            setChild(arr, child)
          })
        }
        return item
      }
      if (data.groups) {
        const list1 = data.groups.find(f => f.name == 'Crm')
        const list2 = data.groups.find(f => f.name == 'CentralControl')
        if (list1 && list2) {
          let permissions = list1.permissions.concat(list2.permissions)
          let parentList = permissions.filter(item => item.parentName == null)
          parentList.forEach(a => {
            let item = setChild(permissions, a)
            treeList.push(item)
          })
        }
      }
      this.authOptions = treeList
      this.checkedKeys = checkedArray
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .role-add {
  .el-form-item {
    padding: 0;
  }
}
</style>
